package Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.model.LatLng;
import com.zcfeng.ischool.CommunityActivity;
import com.zcfeng.ischool.LoginActivity;
import com.zcfeng.ischool.MapActivity;
import com.zcfeng.ischool.MyApp;
import com.zcfeng.ischool.R;
import com.zcfeng.ischool.SchoolWayActivity;
import com.zcfeng.ischool.UserinfoActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import utils.MapUtils;
import utils.MyConstaints;
import utils.SPUtils;
import utils.ToastUtils;

public class CampusFragment extends Fragment implements  AMapLocationListener {
	GridView lv;
	MyApp app;
	public AMapLocationClientOption mLocationOption = null;
	AMapLocation  location;
	int times=0;
	private AMapLocationClient locationClient = null;
	public String[] item = {"校园攻略", "圈子", "学院地图", "早签到", "个人信息", "举报", "修改密码", "注销用户", "退出程序"};
	private int[] icon = {R.drawable.gl, R.drawable.qz, R.drawable.dt, R.drawable.qd, R.drawable.grxx, R.drawable.jb, R.drawable.mmxg, R.drawable.zx, R.drawable.out};
    Handler tiphandler;
    Handler changehandler;
    Handler sgin;
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		//为fragment设置layout
		View view = inflater.inflate(R.layout.fragment_campus, container, false);
		initview(view);
		tiphandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				String res = msg.obj.toString();
				if (res.equals("1")) {
					ToastUtils.safeToast(getActivity(), "举报成功，相关人员会尽快与您联系核实情况");
				}
			}
		};
		changehandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				String res = msg.obj.toString();
				if (res.equals("1")) {
					ToastUtils.safeToast(getActivity(), "密码修改成功");
				}
			}
		};
        sgin= new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String res = msg.obj.toString();
                if (res.equals("1")) {
                    ToastUtils.safeToast(getActivity(), "签到成功");
                }
            }
        };
		app = (MyApp) getActivity().getApplication();
		;
		app.addHandle(MyConstaints.tip, tiphandler);
		app.addHandle(MyConstaints.changepwd, changehandler);
		locationClient = new AMapLocationClient(this.getActivity());
		mLocationOption = new AMapLocationClientOption();
		//设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
		mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
		mLocationOption.setLocationCacheEnable(false);
		locationClient.setLocationOption(mLocationOption);
		locationClient.setLocationListener(this);
		locationClient.startLocation();
		return view;
	}

	private void initview(View view) {
		lv = (GridView) view.findViewById(R.id.map_lv);
		setadapter();
		lv.setOnItemClickListener(new OnItemClickListener() {
			private Intent intent;
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long lid) {
				LayoutInflater inflater;
				View layout;
				switch (position) {
					case 0:
						intent = new Intent(getActivity(), SchoolWayActivity.class);
						startActivity(intent);
						break;
					case 1:
						intent = new Intent(getActivity(), CommunityActivity.class);
						startActivity(intent);
						break;
					case 2:
						intent = new Intent(getActivity(), MapActivity.class);
						startActivity(intent);
						break;
					case 3:
						Time t = new Time();
						t.setToNow();
//						if (t.hour > 7) {
//							ToastUtils.safeToast(getActivity(), "早签到的的时间为每天早上7：10之前！！！请明天再来");
//							break;
//						} else if (t.hour == 7 && t.minute <= 10) {
//							ToastUtils.safeToast(getActivity(), "早签到的的时间为每天早上7：10之前！！！请明天再来");
//							break;
//						}
						System.out.println(t.hour);
                        double x=location.getLatitude();
                        double y=location.getLongitude();
						float distance = MapUtils.getdistance(new LatLng(x, y), SPUtils.getString(getActivity(), MyConstaints.ACADEMY, ""));
                        JSONObject json = new JSONObject();
                        try {
                            json.put("type", "signed");
                            json.put("id", SPUtils.getString(getActivity(), MyConstaints.ID, ""));
                            json.put("x", x);
                            json.put("id", y);
                            json.put("address",location.getAddress());
                            String str = json.toString();
                            Message msg = new Message();
                            msg.what = MyConstaints.send;
                            msg.obj = str;
                            app.getSocket().revHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
						if (distance >=0&&distance<=100) {

							ToastUtils.safeToast(getActivity(),"签到成功");
						}
                        else
                            ToastUtils.safeToast(getActivity(), "距离签到点还有" + distance + "米");
						break;
					case 4:
						startActivity(new Intent(getActivity(), UserinfoActivity.class));
						break;
					case 5:
						inflater = getActivity().getLayoutInflater();
						layout = inflater.inflate(R.layout.event_dd,
								(ViewGroup) getActivity().findViewById(R.id.dialog));
						final EditText id = (EditText) layout.findViewById(R.id.id);
						final EditText content = (EditText) layout.findViewById(R.id.content);
						final EditText tel = (EditText) layout.findViewById(R.id.tel);
						new AlertDialog.Builder(getActivity()).setTitle("举报").setView(layout)
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										gettipresult(id.getText().toString(), content.getText().toString(), tel.getText().toString());
									}
								})
								.setNegativeButton("取消", null).show();
						break;
					case 6:
						inflater = getActivity().getLayoutInflater();
						layout = inflater.inflate(R.layout.event_cc,(ViewGroup) getActivity().findViewById(R.id.dialog));
						final EditText pwd = (EditText) layout.findViewById(R.id.pwd);
						final EditText repwd = (EditText) layout.findViewById(R.id.repwd);
						new AlertDialog.Builder(getActivity()).setTitle("密码修改").setView(layout)
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										if ((pwd.getText().toString()).equals(repwd.getText().toString())) {
											JSONObject json = new JSONObject();
											try {
												json.put("type", "changepwd");
												json.put("id", SPUtils.getString(getActivity(), MyConstaints.ID, ""));
												json.put("pwd", pwd.getText().toString());
												String str = json.toString();
												Message msg = new Message();
												msg.what = MyConstaints.send;
												msg.obj = str;
												app.getSocket().revHandler.sendMessage(msg);
											} catch (JSONException e) {
												e.printStackTrace();
											}
										} else {
											ToastUtils.safeToast(getActivity(), "两次密码不一致");
										}
									}
								})
								.setNegativeButton("取消", null).show();
						break;
					case 7:
						new AlertDialog.Builder(getActivity()).setTitle("确定注销，重新登录？")
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										SPUtils.putBoolean(getContext(), MyConstaints.ISLOGIN, false);
										startActivity(new Intent(getActivity(), LoginActivity.class));
										getActivity().finish();
									}
								})
								.setNegativeButton("取消", null).show();
						break;
					case 8:
						new AlertDialog.Builder(getActivity()).setTitle("确定退出程序")
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										System.exit(0);
									}
								})
								.setNegativeButton("取消", null).show();
						break;
				}
			}
		});
	}
	public void gettipresult(String id, String content, String tel) {
		JSONObject json = new JSONObject();
		try {
			json.put("type", "tip");
			json.put("id", id);
			json.put("content", content);
			json.put("tel", tel);
			String str = json.toString();
			Message msg = new Message();
			msg.what = MyConstaints.send;
			msg.obj = str;
			app.getSocket().revHandler.sendMessage(msg);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void setadapter() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < icon.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("image", icon[i]);
			map.put("text", item[i]);
			list.add(map);
		}
		String[] from = {"image", "text"};
		int[] to = {R.id.image, R.id.text};
		lv.setAdapter(new SimpleAdapter(getActivity(), list, R.layout.item, from, to));
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public void onLocationChanged(AMapLocation aMapLocation) {
		if (aMapLocation != null) {
			if (aMapLocation.getErrorCode() == 0) {
//可在其中解析amapLocation获取相应内容。
				location=aMapLocation;
				times++;
			} else {
				//定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
				Log.e("AmapError", "location Error, ErrCode:"
						+ aMapLocation.getErrorCode() + ", errInfo:"
						+ aMapLocation.getErrorInfo());
			}
		}
	}
}